<body>
    <div class="hd">
        <div class="warp">
            <ul class="btn-list">
                <li class="item">

                    <a href="<?php echo $base_url?>home/order/shoppingcar" class="shop-car bg">
                        <!--<div class="num">1</div>-->
                        <i class="icon iconfont icon-icon"></i>
                    </a>
                </li>
                <li  class="item">
                     <!--<a href="./register.html">
                        <i class="iconfont icon-wode"></i>请登录
                    </a>-->
                    <?php if(isset($user)){?>
                    <span href="#" class="bg">
                        <i class="icon iconfont icon-wode"></i><?php echo $user->mobile;?>
                    </span>
                    
                    <ul class="child-item">
                            <li><a href="<?php echo $base_url?>home/order/userorders">我的订单</a></li>
                            <li><a href="<?php echo $base_url?>home/address">收货地址</a></li>
                            <li><a href="<?php echo $base_url;?><?php if(!empty($cardid)){echo 'home/card/cardlist';}else{echo 'home/card/addcard';}?>">绑定银行卡</a></li>
                            <li><a href="<?php echo $base_url?>home/account/logout">退出商城</a></li>
                    </ul>
                    <?php }else{?>
                    <a href="<?php echo $base_url?>home/account/login?back_url=<?php echo urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); ?>">
                        <i class="iconfont icon-wode"></i>请登录
                    </a>
                    <?php }?>
                </li>
            </ul>
            <a href="<?php echo $base_url?>home/goods/index">
            <img src="<?php echo $base_url?>static/dist/images/logo.png" alt="" class="logo-img">
             <span class="span_txt">商城首页</span>
            </a>
        </div>
    </div>
    <div class="address-bar">
        <div class="warp">
            <p class="tit">
                <a class="r" href="#" id="addAddrBtn">新增收货地址</a> 收货地址
            </p>
            <ul>
                <?php foreach ($content as $value) : ?>
                    <li class="address-item <?php echo $value['default'] ? 'active' : '' ?>" data-addressid="<?php echo $value['address_id']?>" data-value="<?php echo $value['province'];?>/<?php echo $value['city'];?>/<?php echo $value['district'];?>" data-text="<?php echo $value['province_text'];?>/<?php echo $value['city_text'];?>/<?php echo $value['district_text'];?>">
                        <p class="name">
                            <?php echo $value['consignee']; ?>
                        </p>
                        <p class="phone"><?php echo $value['mobile']; ?></p>

                        <p class="address_txt" data-provinceid="<?php echo $value['province'];?>" data-cityid="<?php echo $value['city'];?>" data-districtid="<?php echo $value['district'];?>"><?php echo $value['province_text'] . $value['city_text'] . $value['district_text'] . $value['address']; ?></p>
                        <div class="address_ft">
                            <a href="#123" class="r edit_btn" data-addressid="<?php echo $value['address_id']?>">修改本地址</a>
                            <a class="l" data="<?php echo $value['address_id']?>"><?php echo $value['default'] ? "默认地址" : "设置为默认地址";?></a>
                        </div>
                    </li>
                <?php endforeach; ?>
                <li class="address-item no-address">
                    <i class="iconfont icon-tianjia1"></i>
                    <p>新增收货地址</p>
                </li>
                <!-- <li class="address-item active" data-value="2/52/502" data-text="北京/北京市/东城区">
                    <p class="name">
                        王小二
                    </p>
                    <p class="phone">18288688888</p>

                    <p class="address_txt">广东深圳南山区南新路多少号啥楼啥号哈哈哈 水电费的风格</p>
                    <div class="address_ft">
                        <a href="#123" class="r edit_btn">修改本地址</a>
                        <a href="#1" class="l">默认地址</a>
                    </div>
                </li>
                <li class="address-item" data-value="6/88/801" data-text="广东/汕头/金平区">
                    <p class="name">
                        王小二
                    </p>
                    <p class="phone">18288688888</p>

                    <p class="address_txt">广东深圳南山区南新路多少号啥楼啥号哈哈哈 水电费的风格</p>
                    <div class="address_ft">
                        <a href="#123" class="r edit_btn">修改本地址</a>
                        <a href="#1" class="l">默认地址</a>
                    </div>
                </li>
                <li class="address-item">
                    <p class="name">
                        王小二
                    </p>
                    <p class="phone">18288688888</p>

                    <p class="address_txt">广东深圳南山区南新路多少号啥楼啥号哈哈哈 水电费的风格</p>
                    <div class="address_ft">
                        <a href="#123" class="r edit_btn">修改本地址</a>
                        <a href="#1" class="l">默认地址</a>
                    </div>
                </li>
                <li class="address-item no-address">
                    <i class="iconfont icon-tianjia1"></i>
                    <p>您还没有收货地址</p>
                </li> -->
            </ul>
        </div>
    </div>

    <div class="pay-bar">
        <div class="warp">
            <p class="tit">
                支付方式
            </p>
            <ul class="pay-type">
                <li class="pay-item active" data-paytype='2'>
                    <i class="iconfont icon-zhifu"></i>
                    <span>支付宝</span>
                </li>
                <li class="pay-item" data-paytype='1'>
                    <i class="iconfont icon-ananzuiconv267"></i>
                    <span>微信</span>
                </li>

                <!-- <li class="pay-item">
                    <img src="<?php echo $base_url?>static/dist/images/qdd-ico.jpg" alt="">
                </li> -->
            </ul>
        </div>
    </div>

    <div class="order-msg-list">
        <div class="warp">
            <p class="tit">
                订单信息
            </p>
            <ul class="order-list">
                <?php foreach($goodsInfo as $key => $value): ?>
                <li class="order-item" data-goods_id='<?php echo $value['goods_id']; ?>' data-quantity='<?php echo $value['amount']; ?>'>
                    <div class="l_img">
                        <img src="<?php echo $value['img_path']; ?>" alt="">
                    </div>
                    <div class="r_msg">
                        <p class="name"><?php echo $value['name']; ?></p>
                        <p class="msg"><?php echo $value['other_name']; ?></p>
                    </div>
                    <div class="r_msg2">
                        <p class="r">
                            <span class="price"> <span>¥</span><?php echo $value['price']; ?></span>
                            <span class="num">X<?php echo $value['amount']; ?></span>
                        </p>
                        <!-- <p class="sku">颜色分类：黄色；</p> -->

                    </div>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>

    <div class="remarks-bar">
        <div class="warp">
            <div class="remarks-txt">
                <span>买家备注：</span>
                <input type="text" placeholder="选填，对本次交易订单的说明" id='leave'>
            </div>
            <div class="sub-box">
                <p class="type"><span>支付方式：</span> <span class="val pay-type" id='paytype'>支付宝</span> </p>
                <p class="type"><span>配送方式：</span> <span class="val ">快递免邮</span> </p>
                <p class="type"><span>应付：</span> <span class="val price"> <span>¥</span><?php echo $price; ?></span>
                </p>
                <a href="#123" class="sub-btn" data-enable='1'>提交订单</a>
            </div>
        </div>
    </div>

    <div class="pd-200"></div>

    <?php $this->load->view('home/pc/comm'); ?>

    <div class="mask-box none">
    </div>
    <div class="add_address" id="add_address">
        <div class="bg">
            <a class="col_btn">
                <i class="iconfont icon-icon1"></i>
            </a>
            <p class="tit">新增收货地址</p>
            <div class="cont">
                <div class="input_txt2" id="location">
                    <span>所在地区</span>
                    <div class="picker-warp">
                        <!-- container -->
                        <input id="city-picker1" readonly type="text">
                        <!--<input id="city-picker1" readonly type="text" data-value="2/52/502">-->

                    </div>
                </div>
                <div class="input_txt">
                    <span>详细地址</span>
                    <input type="text" placeholder="请填写详细地址" id="address" maxlength="30" min="6">
                </div>
                <div class="input_txt">
                    <span>收货人</span>
                    <input type="text" id="consignee" min="2" maxlength="15">
                </div>
                <div class="input_txt phone">
                    <span>联系电话</span>
                    <div class="qh">0086</div>
                    <span class="line">一</span>
                    <input type="text" id="mobile" maxlength="11">
                </div>

                <div class="pd50"></div>
                <a href="#123" class="save-btn">保存</a>
            </div>
        </div>
    </div>

    <div class="add_address" id="edit_address">
        <div class="bg">
            <a class="col_btn">
                <i class="iconfont icon-icon1"></i>
            </a>
            <p class="tit">新增收货地址</p>
            <div class="cont">
                <div class="input_txt2">
                    <span>所在地区</span>
                    <div class="picker-warp">
                        <!-- container -->
                        <input id="city-picker2" readonly type="text">
                        <input type="hidden" id="address_ids" value="">
                        <!--<input id="city-picker1" readonly type="text" data-value="2/52/502">-->

                    </div>
                </div>
                <div class="input_txt">
                    <span>详细地址</span>
                    <input type="text" placeholder="请填写详细地址" id="edit_address2"  maxlength="30" min="5">
                </div>
                <div class="input_txt">
                    <span>收货人</span>
                    <input type="text" id="edit_username"  min="2" maxlength="15">
                </div>
                <div class="input_txt phone">
                    <span>联系电话</span>
                    <div class="qh">0086</div>
                    <span class="line">一</span>
                    <input type="text" id="edit_mobile"  maxlength="11">
                </div>

                <div class="pd50"></div>
                <a href="#123" class="save-btn">保存</a>
            </div>
        </div>
    </div>


    <div class="pay_modal">
        <div class="bg">
            <p class="tit">收款方：深圳市养悦源健康产业有限公司</p>
            <a class="col_btn">
                <i class="iconfont icon-icon1"></i>
            </a>
             <div class="cont">
                 <p class="sm-msg">扫一扫付款（元)</p>
                 <p class="price"><?php echo $price; ?></p>
                 <div class="qrCode-box">
                     <img src="" alt="">
                 </div>
                 <p class="ft_msg">打开手机<span id='modal_paytype'>支付宝</span></p>
                 <p class="ft_msg">扫一扫继续付款</p>
                 
             </div>
        </div>
         
    </div>

    <script src="<?php echo $base_url?>static/dist/js/lib/jquery.min.js"></script>
    <script src="<?php echo $base_url?>static/dist/js/lib/city-picker.js"></script>
    <?php $this->load->view('home/pc/footer_js');?>
    <script>
        
        $('.pay-item').on('click', function(){
            $('.pay-item').removeClass('active');
            $(this).addClass('active');
            $('#paytype').html($(this).find('span').html());
            $('#modal_paytype').html($(this).find('span').html());
        });
        var api = {
            province_url: '<?php echo $base_url; ?>home/address/getZonesByID?zoneid=1',
            other_url: '<?php echo $base_url; ?>home/address/getZonesByParentID',
        }
        var dataPicker = {
            PROVINCE_DATA: null,
            CITY_DATA: null,
            DISTRICT_DATA: null
        }
        var $citypicker1,$citypicker2;
        getProvinceData(function (data) {
            provinceData = formatProvince(data);
            dataPicker.PROVINCE_DATA = provinceData;
            $citypicker1 = $('#city-picker1');
            $citypicker1.citypicker({
                spanClick: spanClickFn,
                data: dataPicker
            });

            $("body").on('click', ".no-address", function () {
                $('#add_address').addClass('active');
                $('.mask-box').removeClass('none');
                $citypicker1.citypicker("reset");
            })

            $('body').on('click', '.edit_btn', function () {
                $('#edit_address').addClass('active');
                $('.mask-box').removeClass('none');
                var $this = $(this);
                var valStr = $this.parents(".address-item").data("value");
                var txtStr = $this.parents(".address-item").data("text");
                var valArr = formatDataStr(valStr)
                var txtArr = formatDataStr(txtStr)

                if (valArr[0]) {
                    getData(valArr[0], true, dataPicker, function () {
                        if (valArr[1]) {
                            getData(valArr[1], false, dataPicker, function () {
                                if($citypicker2){
                                    $citypicker2.citypicker("reset");
                                    $('#edit_address').find(".picker-warp").find('.city-picker-span').remove();
                                    $('#edit_address').find(".picker-warp").find('.city-picker-dropdown').remove();
                                }

                                $citypicker2 = $('#city-picker2');
                                $citypicker2.citypicker({
                                    spanClick: spanClickFn,
                                    data: dataPicker,
                                    everyCreate:true, //每次都创建
                                    province: txtArr[0] || "",
                                    city: txtArr[1] || "",
                                    district: txtArr[2] || "",
                                })

                            });
                        }
                    });
                }

				return false;
            })
        })

        function spanClickFn(el, cb) {
            var code = $(el).data('code');
            var province = false;
            var city = false;
            if ($(el).parents(".province").length != 0) {
                province = true;
            } else if ($(el).parents(".city").length != 0) {
                city = true;
            } else if ($(el).parents(".district").length != 0) {
                cb();
                return true;
            }
            $.ajax({
                'url': api.other_url + "?zoneid=" + code,
                type: 'get',
                success: function (data) {
                    data = JSON.parse(data);
                    if (province) {
                        dataPicker.CITY_DATA = formatOtherData(data);
                        dataPicker.DISTRICT_DATA = null;
                    } else {
                        dataPicker.DISTRICT_DATA = formatOtherData(data);
                    }
                    // $this.refresh();
                    cb();
                }
            });
        }

        function getData(code, province, dataPicker, cb) {
            $.ajax({
                'url': api.other_url + "?zoneid=" + code,
                type: 'get',
                success: function (data) {
                    data = JSON.parse(data);
                    if (province) {

                        dataPicker.CITY_DATA = formatOtherData(data);
                    } else {
                        dataPicker.DISTRICT_DATA = formatOtherData(data);

                    }
                    // $this.refresh();
                    cb();
                }
            })
        }

        function formatDataStr(str) {
            var arr = [];
            if (!str) return [];
            return str.split('/');
        }

        function formatProvince(data) {
            var newArr = [], newObj = {};
            for (var i = 0; i < data.length; i++) {
                // newObj[data[i].id] =  data[i].name;
                var dataTmp = {}
                dataTmp.code = data[i].id;
                dataTmp.address = data[i].name;
                newArr.push(dataTmp);
            }
            newObj[" "] = newArr
            return newObj;

        }
        function getProvinceData(cb) {
            $.ajax({
                'url': api.province_url,
                type: 'get',
                success: function (data) {
                    data = JSON.parse(data);
                    cb(data);
                },
                error: function () {
                    console.log('Ajax Error!');
                }

            });
        }
        function formatOtherData(data) {
            var newObj = {};
            if (data == null) {
                return newObj;
            }
            for (var i = 0; i < data.length; i++) {
                // newObj[data[i].id] =  data[i].name;
                newObj[data[i].id] = data[i].name
            }
            return newObj;
        }
        function isEmptyObject(obj) {
            for (var key in obj) {
                return false;
            }
            return true;
        }


    </script>
    <script>
    $(function () {
        

        //获取queryString中的参数
        function getQueryString(name) { 
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
            var r = window.location.search.substr(1).match(reg); 
            if (r != null) return unescape(r[2]); return null; 
        } 

        //清理购物车缓存
        function clearCartStorage()
        {
            var goods = JSON.parse(getQueryString('data'));
            // var cart_goods = JSON.parse(localStorage.getItem('cartData'));
            var cart_goods = getCookie('cartData') || [];		
            if(cart_goods != null && goods != null)
            {
                for(var i = 0;i < goods.length;i++)
                {
                    var goods_id = goods[i].goods_id;
                    for(var j = 0;j < cart_goods.length;j++)
                    {
                        if(goods_id == cart_goods[j].id)
                        {
                            cart_goods.splice(j, 1);
                        }
                    }
                }
                // localStorage.setItem('cartData', JSON.stringify(cart_goods));
				setCookie('cartData',cart_goods,2)
            }
        }
		function setCookie(cname, cvalue, exdays) {
				cvalue = JSON.stringify(cvalue)

				var d = new Date();
				d.setTime(d.getTime() + (exdays*60*60*1000));
				var expires = "expires="+d.toUTCString();
				document.cookie = cname + "=" + cvalue + "; " + expires + ";path=/";  
			}
		function getCookie(cname) {
			var name = cname + "=";
			var ca = document.cookie.split(';');
			for(var i=0; i<ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1);
				if (c.indexOf(name) != -1){
					return JSON.parse(c.substring(name.length, c.length));
				} 
			}
			return "";
		}

        //设置默认地址
        $('body').on('click', '.address-item .l', function(){
            var id = $(this).attr('data');

            $.ajax({
                url: "<?php echo $base_url; ?>home/Users/addDefaultUserAddress/",
                data: {
                    address_id: id
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    console.log(data);
                    if (data.result == 0) {
                        location.reload();
                    } else {
                        alert(data.errmsg);
                    }
                }
            });
        });


        //点击任意收货地址选中
         $('body').on('click', '.address-bar li', function(){
            $('.address-bar li').removeClass('active');
            $(this).addClass('active');
            // return false;
        });

        //点击修改收货地址
        $('body').on('click', '.edit_btn', function(event){
            var address_id = $(this).attr('data-addressid');
            $.ajax({
                url: "<?php echo $base_url; ?>home/address/getAddressByAid?"+"address_id="+address_id,
                dataType: 'json',
                type: 'GET',
                success: function (data) {
                    if (data.result == 0) {
                        $('#edit_address2').val(data.errmsg.address);
                        $('#edit_mobile').val(data.errmsg.mobile);
                        $('#edit_username').val(data.errmsg.consignee);
                        $('#address_ids').val(data.errmsg.address_id);
                    } else {
                        alert(data.errmsg);
                    }
                }
            });
        });


        // 修改收货地址时  数据保存
        $("#edit_address").on('click','.save-btn',function(){
           var selArr = $("#edit_address").find(".city-picker-span .title").find(".select-item");
           var selValArr = [];
           selArr.each(function(i,el){
               selValArr.push($(el).data('code'));
           })

            var address = $("#edit_address2").val().trim();
            var consignee = $("#edit_username").val().trim();
            var mobile = $("#edit_mobile").val().trim();
            var address_id = $('#address_ids').val();

            var provinceid = selValArr[0];
            var cityid = selValArr[1];
            var districtid =selValArr[2];


            if( consignee == '' || mobile == '' || address == '' ||
                provinceid == undefined || cityid == undefined)
            {
                alert('请补全收货地址信息');
                return;
            }
            if(consignee.length < 2 || consignee.length > 15)
            {
                alert('收货人填写错误');
                return;
            }
            var pattern = /^1[34578]\d{9}$/;
            var pattern_tel = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
            if(!(pattern.test(mobile) || pattern_tel.test(mobile))){
                alert("请填写正确的号码");
                return;
            }
            if(address.length < 5)
            {
                alert('详细地址输入不完整');
                return;
            }
            if(address.length>30)
            {
                alert('收货地址太长');
                return;
            }
            if (districtid == undefined)
            {
                districtid = 0;
            }
            $.ajax({
                url: "<?php echo $base_url; ?>home/address/updateAddress",
                data: {
                    'address_id': address_id,
                    'consignee': consignee,
                    'mobile': mobile,
                    'provinceid': provinceid,
                    'cityid': cityid,
                    'districtid': districtid,
                    'address': address
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    if (data.result == 0) {
                        location.reload();
                    } else {
                        alert(data.errmsg);
                    }
                }
            });

        })

        //点击新增收货地址，弹出窗口
        $('#addAddrBtn').on('click', function(){
            $('#add_address').addClass('active');
            $('.mask-box').removeClass('none');
        });

        // 新增收货地址时  数据保存
        $("#add_address").on('click','.save-btn',function(){
            var consignee = $('.add_address #consignee').val().trim();
            var mobile = $('.add_address #mobile').val().trim();
            var address = $('.add_address #address').val().trim();
            var provinceid = $('.add_address #location .title [data-count="province"]').data('code');
            var cityid = $('.add_address #location .title [data-count="city"]').data('code');
            var districtid = $('.add_address #location .title [data-count="district"]').data('code');
            if( consignee == '' || mobile == '' || address == '' ||
                provinceid == undefined || cityid == undefined )
            {
                alert('请补全收货地址信息');
                return;
            }
            var pattern = /^1[34578]\d{9}$/;
            var pattern_tel = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
            if(!(pattern.test(mobile) || pattern_tel.test(mobile))){
                alert("请填写正确的号码");
                return;
            }
            if(consignee.length<2 || consignee.length>15 )
            {
                alert('收货人填写错误');
                return;
            }
            if(address.length < 5)
            {
                alert('详细地址输入不完整');
                return;
            }
            if(address.length>30)
            {
                alert('收获地址太长');
                return;
            }
            if (districtid == undefined)
            {
                districtid = 0;
            }
            $.ajax({
                url: "<?php echo $base_url; ?>home/address/add",
                data: {
                    'consignee': consignee,
                    'mobile': mobile,
                    'provinceid': provinceid,
                    'cityid': cityid,
                    'districtid': districtid,
                    'address': address
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    if (data.result == 0) {
                        location.reload();
                    } else {
                        alert(data.errmsg);
                    }
                }
            });

        })
		$('#leave').on('input',function(){
			if($(this).val().length>30){
				$(this).val($(this).val().slice(0,30))
			}
		})
        //点击提交订单
        $('.sub-btn').on('click', function(){
            //data-enable 属性防止重复点击
            if($(this).data('enable') == 1)
            {
                $(this).data('enable', 0);
                payType = $('.pay-item.active').data('paytype');
                address_id = $('.address-bar .address-item.active').data('addressid');
                var selArr=[];
                $('.order-item').each(function(){
                    var selObj = {};
                    selObj.goods_id = $(this).data('goods_id');
                    selObj.quantity = $(this).data('quantity');
                    selArr.push(selObj);
                });                

                $.post("<?php echo $base_url; ?>home/order/confirm", 
                        { paytype:payType, goods:selArr, leave:$('#leave').val(), address_id:address_id},  
                       function(data){  
                         $('.sub-btn').data('enable', 1);
                         if(data.errcode != 0)
                         {
                            alert(data.errmsg);
                         } 
                         else
                         {
                            //下单成功，清理购物车本地缓存
                            clearCartStorage();
                            //重置购物车图标
                            $('.shop-car .num').remove();
                            //支付宝支付
                            if(payType == 2){
                                $.post("<?php echo $base_url; ?>ajax/payment/zhifbscpay",{order_id:data.orderid},function(result){
                                    // console.log(result);
                                    $('.mask-box').removeClass('none');
                                    $('.pay_modal').addClass('active');
                                    $('.pay_modal .qrCode-box img').attr('src', result.code_img_url);
                                },"json");
                            }

                            //微信支付
                            if(payType == 1){
                                $.post("<?php echo $base_url; ?>ajax/payment/wxinpay",{order_id:data.orderid},function(result){
                                    // console.log(result);
                                    $('.mask-box').removeClass('none');
                                    $('.pay_modal').addClass('active');
                                    $('.pay_modal .qrCode-box img').attr('src', result.code_img_url);
                                },"json");
                            }
							if(data.orderid){
							 	startPayTimer(data.orderid);								
							}
                         }
                       }, 
                        "json");
                }
        });
		function getStatus(orderid){				
			$.ajax({
				url:"/ajax/Order/CheckOrderTimeOut",
				data:{"order_id":orderid},
				type:"POST",
				success:function(data){
					data = JSON.parse(data);
					if(data.errcode == 0){
						successVal =true;	
						location.href = '/home/order/orderinfo?orderid='+orderid;
					}else if(data.errcode == 1){
						successVal =false;
					}
				},
				error:function(err){
					console.log('Ajax Error');
				}
			})
		}

		var PayTimer = null, successVal = false;
		
		$('.col_btn').on('click', function () {
            $('.mask-box').addClass('none');
            $(this).parents('.add_address').removeClass('active');
            $(this).parents('.pay_modal').removeClass('active');    
			clearTimeout(PayTimer)       			
        })

				
		function startPayTimer(orderid){
			function loopPayTimerFn(){
				PayTimer = setTimeout(function() {
					getStatus(orderid);
					if(!successVal){
						loopPayTimerFn();
					}						
				}, 2000);
			}	
			loopPayTimerFn();
		}
    })
    </script>
</body>

</html>
